package com.derbysoft.dswitch.adapter.ihg.webservice.handler;

import com.derbysoft.dswitch.adapter.ihg.common.domain.Direction;
import com.derbysoft.dswitch.adapter.ihg.common.log.LogDetailPair;
import com.derbysoft.dswitch.adapter.ihg.common.log.TransactionLogger;
import com.derbysoft.dswitch.adapter.ihg.common.utils.ErrorMessageUtils;
import com.derbysoft.dswitch.adapter.ihg.exception.InvokeProviderSideException;
import com.derbysoft.dswitch.adapter.ihg.dto.Request;
import com.derbysoft.dswitch.adapter.ihg.dto.Response;
import com.derbysoft.dswitch.adapter.ihg.webservice.ProviderWebService;
import com.derbysoft.dswitch.adapter.ihg.webservice.impl.AccountProvider;
import com.derbysoft.dswitch.adapter.ihg.webservice.impl.RequestPair;
import com.derbysoft.dswitch.adapter.ihg.webservice.impl.ResponsePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by: jason
 * Date: 2012-05-22
 */
@Component("bookWebServiceHandler")
public class BookWebServiceHandlerImpl<RQ extends Request, RS extends Response>
        extends AbstractWebServiceHandler implements WebServiceHandler<RQ, RS> {

    @Autowired
    @Qualifier("bookingProviderWebService")
    private ProviderWebService<RQ, RS> bookingProviderWebService;

    @Override
    public RS invoke(RQ request, boolean serveReservation, AccountProvider accountProvider) {
        Set<LogDetailPair> logDetails = TransactionLogger.getLogDetails().get();
        if (logDetails == null) {
            logDetails = new HashSet<LogDetailPair>();
        }
        logDetails.add(LogDetailPair.build(request, Direction.TO_HOTEL));
        try {
            return bookingProviderWebService.invoke(request, accountProvider);
        } catch (Exception ex) {
            TransactionLogger.getReservationLogger().get().setError(true);
            throw new InvokeProviderSideException(ex.getMessage(),ex);
        } finally {
            TransactionLogger.getLogDetails().set(logDetails);
        }
    }

    @Override
    public List<ResponsePair<RQ, RS>> batchInvoke(List<RequestPair<RQ>> requests, AccountProvider accountProvider) {
        throw new UnsupportedOperationException("batchInvoke();");
    }
}
